import requests
import json
import os
from datetime import datetime

# 配置参数
DING_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=c061f5a887e77fe36269ea1e45fb727e7b70de5d55509ae389e4a4fd2825c502"
REPORT_URL = "http://172.26.21.172:8888/reports/reportAllure/"  # 替换为实际报告地址
PROJECT_NAME = "学网课堂API"


# 从Allure报告中提取统计数据
def get_allure_stats(report_dir=os.path.abspath(os.path.join(os.getcwd()))+"\\reports\\reportAllure"):
    history_file = os.path.join(report_dir, "history", "history-trend.json")
    with open(history_file, 'r') as f:
        history = json.load(f)
    return history[-1]  # 获取最新一次统计


# 构建钉钉消息
def build_message():
    stats = get_allure_stats()
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    return {
        "msgtype": "markdown",
        "markdown": {
            "title": "自动化API测试报告通知",
            "text": f"""### {PROJECT_NAME}测试结果
**生成时间**：{current_time}  
**通过率**：{stats['data']['passed'] / stats['data']['total'] * 100:.2f}%  
**用例统计**：
- 总用例数：{stats['data']['total']}
- 通过：{stats['data']['passed']} 
- 失败：{stats['data']['failed']}
- 跳过：{stats['data']['skipped']}

[➡️ 查看详细报告]({REPORT_URL})"""
        },
        "at": {
            "isAtAll": False  # 设为True可@所有人
        }
    }


# 发送消息
def send_to_dingtalk():
    message = build_message()
    headers = {"Content-Type": "application/json"}
    response = requests.post(DING_WEBHOOK, headers=headers, data=json.dumps(message))
    print("钉钉机器人响应：", response.text)
